const cmdOutput = document.getElementById('cmd-output');
const cmdInput = document.getElementById('cmd-input');
let __power__whohas = 'UserX';
const commandTable = {
  'help': {
    description: 'show Available commands',
    action: () => {
      cmdOutput.textContent = '';
      cmdOutput.textContent += `----------------------------------------------------------------------------
Available commands:
1. help - Show Available commands. || 2. echo <message> - Show message you entered.
3. clear - Clear screen. || 4. eval <formula> - Number crunching or math. 
5.other - Why not visualize to do this
----------------------------------------------------------------------------
Formal order:
1.select <type> <id> - Inquiry of personal information or designated documents (ID)-
(Type: user, file)
2.listfiles - List all files you uploaded.
3.delete <fileid> - Delete a file you uploaded.
4.update <fileid> <newpwd> - Update the password of designated documents (ID) if newpwd is null, 
it will have no password.
-----------------------------------------------------------------------------
`;
    }
  },
  'echo': {
    description: 'show message you entered',
    action: (args) => {
      if (args.length === 0) {
        cmdOutput.textContent += `No message provided\n`;
        return;
      }
      cmdOutput.textContent += `${args.join(' ')}\n`;
    }
  },
  'clear': {
    description: 'clear screen',
    action: () => {
      cmdOutput.textContent = '';
    }
  },
  'eval': {
    description: 'Number crunching or math',
    action: (args) => {
      if (args.length !== 1) {
        cmdOutput.textContent += `A calculation is required\n`;
        return;
      }
      const num1 = args[0];
      try {
        const result = eval(num1);
        cmdOutput.textContent += `${result}\n`;
      } catch (error) {
        cmdOutput.textContent += `Error in calculation: ${error.message}\n`;
      }
    }
  },
  'other': {
    description: "Why not visualize to do this",
    action: (args) => {
      cmdOutput.textContent += `Maybe it's some unavoidable reason, or maybe it's unspeakable, it's ridiculous, but I think
it's okay.That's what we were all about`;
    }
  },
  'select': {
    description: 'Inquiry of personal information or designated documents (ID)',
    action: (args) => {
      if (args.length < 1) {
        cmdOutput.textContent += `A calculation is required\n`;
        return;
      }
      const type = args[0].toLowerCase();
      const id = args[1];
      if (type !== 'user' && type !== 'file') {
        cmdOutput.textContent += `Invalid type: ${type}\n`;
        return;
      }
      if (type === 'file' && id === undefined || id === null) {
        cmdOutput.textContent += `A file ID is required\n`;
        return;
      }
      const userid = sessionStorage.getItem('user');
      const data = {
        types: type,
        fileid: id,
        userid: userid,
        token: _encok_tokens
      };
      fetch('/apicommand/getinfo/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
        .then(response => {
          if (!response.ok) {
            cmdOutput.textContent += `Error: Abnormal network status\n`;
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            const retudata = data.data;
            let retumoudlecontent = '';
            if (type === 'user') {
              retumoudlecontent = `------Here's your information------
Bind an email address: ${retudata.bdmail}
Total capacity: ${retudata.capacity}GB Used capacity: ${retudata.capacityed}GB
Total traffic: ${retudata.rate}GB Used traffic: ${retudata.rated}GB
------------------------------------`;
            } else if (type === 'file') {
              let locaplace = retudata.asets;
              if (locaplace.includes('s3::>')) {
                locaplace = 'Nimbus object storage';
              } else {
                locaplace = 'Local storage';
              }
              retumoudlecontent = `------Here's your file information------
File name: ${retudata.names}
Extract the code: ${retudata.pwd}
Upload time: ${retudata.timei}
Storage location: ${locaplace}
Number of downloads: ${retudata.numd}
File size: ${retudata.sizes}MB
------------------------------------`;
            }
            cmdOutput.textContent += `${retumoudlecontent}\n`;
          } else {
            cmdOutput.textContent += `${retudata.message}\n`;
          }
        })
        .catch(error => {
          cmdOutput.textContent += "Error:linking error\n";
        });
    }
  },
  'listfiles': {
    description: 'List all files you uploaded',
    action: () => {
      const userid = sessionStorage.getItem('user');
      const data = {
        userid: userid,
        token: _encok_tokens
      };
      fetch('/apicommand/listfiles/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
        .then(response => {
          if (!response.ok) {
            cmdOutput.textContent += `Error: Abnormal network status\n`;
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            const retudata = data.data;
            retudata.forEach(d => {
              let locaplace = d.asets;
              if (locaplace.includes('s3::>')) {
                locaplace = 'Nimbus object storage';
              } else {
                locaplace = 'Local storage';
              }
             
              cmdOutput.textContent += `\n------${d.names}------
File ID: ${d.id}
File name: ${d.names}
Extract the code: ${d.pwd}
Upload time: ${d.timei}
Storage location: ${locaplace}
Number of downloads: ${d.numd}
File size: ${d.sizes}MB
------------------------------------`;
            });
          } else {
            cmdOutput.textContent += `${retudata.message}\n`;
          }
        })
        .catch(error => {
          cmdOutput.textContent += "Error:linking error\n";
        });
    }
  },
  'delete': {
    description: 'Delete a file',
    action: (args) => {
      if (args.length < 1) {
        cmdOutput.textContent += `A file ID is required\n`;
        return;
      }
      const fileid = args[0];
      const userid = sessionStorage.getItem('user');
      const data = {
        fileid: fileid,
        userid: userid,
        token: _encok_tokens
      };
      fetch('/apicommand/delete/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
        .then(response => {
          if (!response.ok) {
            cmdOutput.textContent += `Error: Abnormal network status\n`;
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            cmdOutput.textContent += `File deleted successfully\n`;
          } else {
            cmdOutput.textContent += `${retudata.message}\n`;
          }
        })
        .catch(error => {
          cmdOutput.textContent += "Error:linking error\n";
        });
    }
  },
  'update': {
    description: 'Update a file',
    action: (args) => {
      if (args.length !== 2) {
        cmdOutput.textContent += `A file ID and new name are required\n`;
        return;
      }
      const filesid = args[0];
      const filenewpwd = args[1];
      const usersid = sessionStorage.getItem('user');
      const data = {
        fileid: filesid,
        pwd: filenewpwd,
        userid: usersid,
        token: _encok_tokens
      };
      fetch('/apicommand/update/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
        .then(response => {
          if (!response.ok) {
            cmdOutput.textContent += `Error: Abnormal network status\n`;
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            cmdOutput.textContent += `File updated successfully\n`
          } else {
            cmdOutput.textContent += `${retudata.message}\n`;
          }
        })
        .catch(error => {
          cmdOutput.textContent += "Error:linking error:";
        });
    }
  },
  'configure-space': {
    description: 'Configure the space for file storage',
    action: (args) => {
      document.getElementById('spaceconfig-id').click();
    }
  }
};

function autoComplete(input) {
  const commands = Object.keys(commandTable);
  const parts = input.split(' ');
  const currentPart = parts[parts.length - 1];
  const suggestions = commands.filter(cmd => cmd.startsWith(currentPart.toLowerCase()));
  cmdOutput.textContent = cmdOutput.textContent.replace(/May command: .*\n?$/, '');
  if (suggestions.length === 0) {
    cmdOutput.textContent = cmdOutput.textContent.replace(/May command: .*\n?$/, '');
    return;
  } else if (suggestions.length === 1) {
    cmdOutput.textContent += `May command: ${suggestions[0]}\n`;
  } else {
    cmdOutput.textContent += `May command: ${suggestions.join(', ')}\n`;
  }
}

cmdInput.addEventListener('input', () => {
  const userInput = cmdInput.value.trim();
  if (userInput) {
    autoComplete(userInput);
  }
});

function processCommandLine(commandLine) {
  const parts = commandLine.match(/"[^"]*"|\S+/g);
  if (!parts) return;

  const command = parts[0].toLowerCase();
  const args = parts.slice(1).map(arg => {
    if (!arg.startsWith('"') && !arg.endsWith('"') && isNaN(arg)) {
      throw new Error(`Invalid argument: ${arg}. Non-numeric arguments must be enclosed in quotes.`);
    }
    return arg.replace(/^"|"$/g, '');
  });

  const commandEntry = commandTable[command];
  if (commandEntry && commandEntry.action) {
    try {
      commandEntry.action(args);
    } catch (error) {
      cmdOutput.textContent += `Error: ${error.message}\n`;
    }
  } else {
    cmdOutput.textContent += `Unknown command: ${command}\n`;
  }
}

cmdInput.addEventListener('keypress', (e) => {
  if (e.key === 'Enter') {
    const commandLine = cmdInput.value.trim();
    cmdInput.value = '';
    if (commandLine) {
      cmdOutput.textContent += `${__power__whohas}:\\> ${commandLine}\n`;
      try {
        processCommandLine(commandLine);
      } catch (error) {
        cmdOutput.textContent += `Error: ${error.message}\n`;
      }
    }
  }
});